/*
 * Operacion.cpp
 *
 *  Created on: 31/05/2011
 *      Author: wadi
 */

#include "operation.h"

#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <string>
#include <sstream>
#include <algorithm>
#include <iterator>

using namespace std;


Operation::Operation() : Message() {
}

Operation::~Operation() {
}

void Operation::setSize(int tamanio) {
  this->size = tamanio;
}
std::vector<std::string> Operation::getTokens(){
  if(tokens.size()==0){
      // Then we parse it
      istringstream iss(getData());
      copy(istream_iterator<string>(iss),
          istream_iterator<string>(),
          back_inserter<vector<string> >(tokens));
  }
  return tokens;
}

std::vector<char>  Operation::getDataBytes(){

  return getDataBytes(0);
}

std::vector<char>  Operation::getDataBytes(int desde){
  vector<char> claveChar;

  int i=desde;
  while (i<(size+5)) {
      claveChar.push_back(buffer[i]);
      i++;
  }
  return claveChar;
}
string Operation::getData() {
  vector<char> claveChar;
  unsigned int i = 5;
  //buffer[i] != '\0'
  while (i<(size+5)) {
      claveChar.push_back(buffer[i]);
      i++;
  }
  claveChar.push_back('\0');
  string s(claveChar.data());
  return s;
}

void Operation::setType(char tipoOperacion) {
  buffer.push_back(tipoOperacion);
}

char Operation::getType() {
  return buffer[0];
}


void Operation::setData(std::string data) {
  this->data= data;
}

std::vector< char> Operation::serialize() {
  this->size = data.size() ;//+ 1;
  serializeSize();
  for (string::iterator it = data.begin(); it != data.end(); it++) {
      char data = *it;
      buffer.push_back(data);
  }
  //TODO buffer.push_back('\0');
  return buffer;
}



void Operation::reset() {
  tokens.clear();
  LOG4CXX_TRACE(logger_, "Comparing for reset sizes "<<size <<" with "<<buffer.size());
  if ((size + 5) < buffer.size()) {
      //  buffer.erase(buffer.begin(), buffer.begin()+(size + 5));
      std::vector< char> aux(buffer.begin()+(size + 5), buffer.end());
      LOG4CXX_TRACE(logger_, "new vector size: "<<aux.size());

      buffer.clear();
      buffer.resize(aux.size());
      std::copy(aux.begin(), aux.end(), buffer.begin());
      LOG4CXX_TRACE(logger_, "buffer size: "<<buffer.size());
      size = 0;
      sizeReaded=false;
      if (buffer.size() >=5){
          size = readInteger(1);
          sizeReaded=true;
          LOG4CXX_TRACE(logger_, "Comparing for reset sizes "<<size );
      }
  } else {
      Message::reset();
      LOG4CXX_TRACE(logger_, "Reseteado  tamanio "<< size );
  }
}
